import { ScrollView } from 'react-native';
import { RefObject } from 'react';

import { Dispatch, Tab, State } from './types';
import { getScreenInfo } from '../../util/screen';
import tracker from '../../util/actionTracker';
import {
  showCourseList,
  showDiscovery,
  showPersonCenter
} from '../../constant/events';
import { TabId } from './constant';
import { getCourseList } from './components/CourseList/actions';
import { AppApi, CourseApi } from '../../api';
import { setGrayList, GrayRow } from '../../store/gray';
import { setUserLessonResourceIds } from '../../util/videoDownload/videoDownloadStore';
import { getSelfCenter } from './components/Person/actions';

const { width } = getScreenInfo({});

let dispatch: Dispatch;
let state: State;
let tabScroll: RefObject<ScrollView>;
let currentTab: Tab;

export default (d: Dispatch, s: State): void => {
  dispatch = d;
  state = s;
};

export const setScroll = (scroll: RefObject<ScrollView>): void => {
  tabScroll = scroll;
};

export const showTabEvent = (id: number): void => {
  if (id === TabId.Discovery) {
    tracker.reportAction(showDiscovery);
    return;
  }
  if (id === TabId.Course) {
    tracker.reportAction(showCourseList);
    return;
  }
  if (id === TabId.Mine) {
    tracker.reportAction(showPersonCenter);
  }
};

export const setCurrentTab = (value: Tab): void => {
  if (tabScroll && tabScroll.current) {
    const { tabs } = state;
    currentTab = value;
    const index = tabs.findIndex((tab): boolean => tab.id === value.id);

    if (index === -1) return;

    tabScroll.current.scrollTo({
      x: width * index,
      y: 0,
      animated: false
    });
    dispatch({ type: 'SET_CURRENT_TAB', value });
  }
};

export const setTabs = (value: Tab[]): void => {
  dispatch({ type: 'SET_TABS', value });
  [currentTab] = value;
};

export const reset = (): void => {
  if (currentTab) {
    setCurrentTab(currentTab);
  }
};

export const getUserLessonResourceIds = async (): Promise<void> => {
  setUserLessonResourceIds([]);
  const res = await CourseApi.getLessonResourceIDs();

  if (res.code === 0) {
    setUserLessonResourceIds(res.data ? res.data.lessonResourceIds : []);
  }
};

export const backAction = (): void => {
  const currentTabId = state.currentTab.id;

  showTabEvent(currentTabId);

  if (currentTabId === TabId.Course) {
    getUserLessonResourceIds();
    getCourseList();
  } else if (currentTabId === TabId.Mine) {
    getSelfCenter();
  }
};

export const getGrayConfig = async (): Promise<void> => {
  const res = await AppApi.getClientConfig();
  const { code, data } = res;
  if (code !== 0) return;

  const { infos = [] } = data || { infos: [] };
  setGrayList(
    infos.map(
      (info): GrayRow => ({
        name: info.name,
        key: info.key,
        list: info.configs,
        full: info.toAll
      })
    )
  );
};
